package com.ruitu.mall_98_seller.ui.home;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruitu.arad.Arad;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.mall_98_seller.R;
import com.ruitu.mall_98_seller.mvp.model.MsgModel;
import com.ruitu.mall_98_seller.mvp.presenter.MsgPresenter;
import com.ruitu.mall_98_seller.ui.msg.MsgListActivity;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.bean.EventModel;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import q.rorbin.badgeview.QBadgeView;

public class MsgFragment extends BaseFragment<MsgPresenter.MsgFragP, MsgModel.MsgFragM> {
    private TextView tv_title, tv_im, tv_sys;//标题,客服聊天,系统消息
    private RelativeLayout rl_sys, rl_chat;//系统消息,客户消息
    private QBadgeView qBadgeViewRong, qBadgeViewSys;//小红点(融云,系统)

    public static MsgFragment newInstance() {
        Bundle args = new Bundle();
        MsgFragment fragment = new MsgFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Arad.bus.register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventMsg(EventModel event) {
        if (event.getEventCode() == 19010251) {// 融云消息数量
            int number = (int) event.getEventObj();
            addBadge(number, qBadgeViewRong, tv_im);
        }
        if (event.getEventCode() == 19090552) {// 收到推送,重新请求系统消息数量
            if (CommonUtils.isLogin()) {
                p.reqUnReadMsgNum(AppHolder.instance().getUser().getCompany().getId());
            }
        }
        if (event.getEventCode() == 19090553) {// 检测到融云未连接,登录成功等操作时,需要重连融云
            if (CommonUtils.isLogin()) {
                p.connectRong();// 连接融云
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (CommonUtils.isLogin()) {
            p.getRongUnReadMsgNum();// 获取融云未读消息数量,完成后会自动获取系统未读消息数量
        } else {
            try {
                qBadgeViewSys.setBadgeNumber(0);
                qBadgeViewRong.setBadgeNumber(0);
                lastBadge = 0;
                ((HomeActivity) getActivity()).addBadge(1, 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_msg, container, false);
        tv_title = v.findViewById(R.id.tv_title);
        tv_im = v.findViewById(R.id.tv_im);
        tv_sys = v.findViewById(R.id.tv_sys);
        rl_sys = v.findViewById(R.id.rl_sys);
        rl_chat = v.findViewById(R.id.rl_chat);

        qBadgeViewRong = new QBadgeView(getActivity());
        qBadgeViewSys = new QBadgeView(getActivity());

        tv_title.setText("消息");

        setOnClickListener(rl_sys, rl_chat);

        return v;
    }

    @Override
    public void onClick(View v) {
        if (v == rl_sys) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(MsgListActivity.class);
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
        }
        if (v == rl_chat) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                /**
                 * 启动会话列表界面。
                 * supportedConversation 定义会话列表支持显示的会话类型，及对应的会话类型是否聚合显示。
                 * 例如：supportedConversation.put(Conversation.ConversationType.PRIVATE.getName(), false) 非聚合式显示 private 类型的会话。
                 */
                Map<String, Boolean> typeMap = new HashMap<>();
                typeMap.put(Conversation.ConversationType.PRIVATE.getName(), false);
                RongIM.getInstance().startConversationList(getActivity(), typeMap);
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
        }
    }

    @Override
    public void onReqComplete(int code, boolean isOk, Object data) {
        if (code == 1) {// 未读消息数量
            int number = 0;
            try {
                number = Integer.parseInt((String) data);
            } catch (Exception e) {
                e.printStackTrace();
            }
            int totalNum = number + p.rongMsgNum;
            // 系统消息数量
            addBadge(number, qBadgeViewSys, tv_sys);
            // 总的消息数量
            ((HomeActivity) getActivity()).addBadge(1, totalNum);

            boolean isMiuiShow = totalNum > lastBadge;// 当前数量大于之前记录的数量,发送显示角标
            Logg.i("lastBadge = " + lastBadge + "    totalNum = " + totalNum);
            p.setBadgeNum(totalNum, getActivity(), isMiuiShow);// 设置桌面角标
            lastBadge = totalNum;// 更新:最后一次记录的未读(角标)消息数量
        }
        if (code == 2) {// 融云连接成功

        }
    }

    private int lastBadge = 0;// 最后一次记录的未读(角标)消息数量,主要适配小米手机桌面角标

    public void addBadge(int number, QBadgeView qBadgeView, View targetView) {// add badge
        try {
            if (number == 0) {
                qBadgeView.hide(true);
            } else {
                qBadgeView.setBadgeNumber(number)
                        .setGravityOffset(1, 14, true)
                        .bindTarget(targetView)
                        .setBadgeTextSize(10, true)
//                        .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
//                            @Override
//                            public void onDragStateChanged(int dragState, Badge badge, View targetView) {
//                                if (Badge.OnDragStateChangedListener.STATE_SUCCEED == dragState) {
////                            Toast.makeText(BadgeViewActivity.this, R.string.tips_badge_removed, Toast.LENGTH_SHORT).show();
//                                }
//                            }
//                        })
                ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
